package com.gongJiao.controller;

import com.gongJiao.Vo.AdminVehicleVo;
import com.gongJiao.Vo.VehicleVo;
import com.gongJiao.Vo.WebVehicleInfo;
import com.gongJiao.Vo.WebVehicleSiteInfo;
import com.gongJiao.common.Result;
import com.gongJiao.entity.*;
import com.gongJiao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 首页控制器
 * @author Administrator
 */
@Controller
public class IndexController {
    @Autowired
    UserService userService;
    @Autowired
    InfoService infoService;
    @Autowired
    NoticeService noticeService;
    @Autowired
    VehicleService vehicleService;
    @Autowired
    SiteService siteService;
    @Autowired
    RouteSiteService routeSiteService;
    @Autowired
    RouteService routeService;//线路
    /**
     * 首页跳转
     * @return
     */
    @GetMapping("")
    public String index(Model model) {
        //获去网站信息
        Info info = infoService.getInfo();
        //获取公告信息
        List<Notice> noticeList = noticeService.getWebNoticeList();
        //获取6条公交信息
        List<Vehicle> vehicleList=vehicleService.getSixVehicle();
        //返回网站信息
        model.addAttribute("info",info);
        model.addAttribute("noticeList",noticeList);
        model.addAttribute("vehicleList",vehicleList);
        return "index";
    }

    @GetMapping("/goUser/{id}")
    public String goUser(Model model, @PathVariable Long id){
        //根据id获取用户对象
        User user = userService.getById(id);
        model.addAttribute("user",user);
        return "userInfo";
    }

    /**
     * 根据id获取公交信息
     * @param id
     * @return
     */
    @GetMapping("/getVehicle/{id}")
    public String getVehicleById(@PathVariable Long id, Model model){
        //获取公交信息
        WebVehicleInfo webVehicleInfo=vehicleService.getwebVehicleInfoById(id);
        //获取公交中间站点信息
        WebVehicleSiteInfo webSiteInfo=vehicleService.getwebVehicleSiteInfoById(id);
        webSiteInfo.setMiddleSite(webSiteInfo.getMiddleSite()!=null?webSiteInfo.getMiddleSite().replaceAll(",","-->"):"");
        model.addAttribute("webVehicleInfo",webVehicleInfo);
        model.addAttribute("webSiteInfo",webSiteInfo);
        return "vehicleInfo";

    }

    /**
     * 公交信息页跳转
     * @return
     */
    @GetMapping("/vehicle")
    public String goVehicle(Model model,String name,Long endSite,Long startSite) {
        //获取站点信息
        List<Site> siteList=siteService.getSiteList();
        //传递站点信息
        model.addAttribute("siteList",siteList);
        //获取公交数据
        /*VehicleVo vehicleVo = new VehicleVo();
        vehicleVo.setStartSite(startSite);
        vehicleVo.setEndSite(endSite);
        vehicleVo.setLimit(10000);
        vehicleVo.setPage(1);
        vehicleVo.setName(name);
        List<AdminVehicleVo> list;
        if(vehicleVo.getStartSite()==null && vehicleVo.getEndSite()==null){
            //根据名字查询以及正常查询
             list=vehicleService.getVehicleList(vehicleVo);
            model.addAttribute("WebVehicleList",list);
        }else {
            //根据路线查询
             list=vehicleService.getVehicleListByRoute(vehicleVo);
            model.addAttribute("WebVehicleList",list);
        }*/
        return "vehicle";
    }

    /**
     * 公交信息页跳转
     * @return
     */
    @GetMapping("/goInquireVehicle")
    @ResponseBody
    public Result goInquireVehicle(HttpSession session, String name, Long endSite, Long startSite) {
        //获取公交数据
        VehicleVo vehicleVo = new VehicleVo();
        vehicleVo.setStartSite(startSite);
        vehicleVo.setEndSite(endSite);
        vehicleVo.setLimit(10000);
        vehicleVo.setPage(1);
        vehicleVo.setName(name);
        List<AdminVehicleVo> list;
        if(vehicleVo.getStartSite()==null && vehicleVo.getEndSite()==null){
            //根据名字查询以及正常查询
            list=vehicleService.getVehicleList(vehicleVo);
        }else if(vehicleVo.getStartSite()!=null && vehicleVo.getEndSite()!=null){
            //查询换乘线路
            String str = busStationToStation(vehicleVo.getStartSite()+"",vehicleVo.getEndSite()+"");
            return Result.fail("300",str,str);
        }else {
            //根据路线查询
            list=vehicleService.getVehicleListByRoute(vehicleVo);
        }
        if (list == null || list.size()==0) {
            return Result.fail("暂无符合结果的公交");
        }else {
            session.setAttribute("list",list);
            return Result.success("查询成功");
        }

    }

    /**
     * 公交搜索结果页面跳转
     * @return
     */
    @GetMapping("/inquireVehicle")
    public String index() {
        return "inquireVehicle";
    }



    //公交换乘线路算法
    // 实现换乘算法的函数
    // 需要提供参数，查询的起点和终点
    public String busStationToStation(String start, String end) {
        boolean start_flag, end_flag;
        String str = "公交车辆";
        start_flag = false;
        end_flag = false;
        String station_total[] = this.getStation();//数据库中所有公交站点名
        String busline_total[] = this.getBusline();//数据库中所有路线
        // 判断数据库中是否有此站点
        for (int i = 0; i < station_total.length; i++) {
            if (start.equals(station_total[i]))
                start_flag = true;
            if (end.equals(station_total[i]))
                end_flag = true;
            if (start_flag && end_flag)
                break;
        }
        if (!(start_flag && end_flag)) {
            str = "站点都不存在!";
        }
        // 两个站点都存在的情况
        // 首先判断有无直达车
        String line_temp = "";
        for (int j = 0; j < busline_total.length; j++) {
            int direct_flag = 0;
            String station_per_line[] = this.stationPerLine(busline_total[j]);
            for (int k = 0; k < station_per_line.length; k++) {
                if (start.equals(station_per_line[k]))
                    direct_flag++;
                if (end.equals(station_per_line[k]))
                    direct_flag++;
                if (direct_flag == 2) {
                    //System.out.println("有直达");
                    break;
                }
            }

            if (direct_flag == 2) {
                line_temp = busline_total[j];
                //查询线路下所有公交名称
                VehicleVo v = new VehicleVo();
                v.setRouteId(Long.parseLong(line_temp));
                v.setLimit(10000);
                v.setPage(1);
                List<AdminVehicleVo> list =  vehicleService.getVehicleList(v);
                for(AdminVehicleVo tt:list) {
                    str += tt.getName() + "、";// 这块可以改成字符串链接—————–
                }
                str += "可直接到达这两个站点";
            }
        }
        // 没有直达车
        if (line_temp == "") {
            //System.out.println("没有直达车，下面进行一次中转的算法");
            String start_pass[] = this.linePerStation(start);
            String end_pass[] = this.linePerStation(end);
            String station_temp = "";// 用来保存站点用的，最后用+连成路径，一次输出三个站点
            for (int s = 0; s < start_pass.length; s++) {
                for (int e = 0; e < end_pass.length; e++) {
                    // 判断两条线路有没有交叉点
                    String start_per_line[] = this.stationPerLine(start_pass[s]);
                    String end_per_line[] = this.stationPerLine(end_pass[e]);
                    for (int ss = 0; ss < start_per_line.length; ss++)
                        for (int ee = 0; ee < end_per_line.length; ee++) {
                            if ((start_per_line[ss]).equals(end_per_line[ee])) {
                                // 成功找到交叉点后
                                // 存储交叉点处信息
                                // 此只为一次换乘
                                String first_line = start_pass[s];
                                String second_line = end_pass[e];
                                String change_station = start_per_line[ss];
                                String siteName = siteService.getSiteById(Long.parseLong(change_station)).getName();

                                //查询线路下所有公交名称
                                VehicleVo v = new VehicleVo();
                                v.setRouteId(Long.parseLong(first_line));
                                v.setLimit(10000);
                                v.setPage(1);
                                List<AdminVehicleVo> list =  vehicleService.getVehicleList(v);
                                String str1 = "";
                                for(AdminVehicleVo tt:list) {
                                    str1 += tt.getName() + "、";// 这块可以改成字符串链接—————–
                                }

                                //查询线路下所有公交名称
                                VehicleVo v2 = new VehicleVo();
                                v2.setRouteId(Long.parseLong(second_line));
                                v2.setLimit(10000);
                                v2.setPage(1);
                                List<AdminVehicleVo> list2 =  vehicleService.getVehicleList(v2);
                                String str2 = "";
                                for(AdminVehicleVo tt:list2) {
                                    str2 += tt.getName() + "、";// 这块可以改成字符串链接—————–
                                }

                                station_temp += "第一步：先乘坐公交" + str1+"到"+ siteName +"站下车"
                                        +"<br/>第二步：在乘坐公交"+ str2  + "";
                            }
                        }
                }
            }
            if (station_temp != "")
                str = "乘车路线如下：<br/>" + station_temp;
            else
                str = "没有查到路线";
        }
        return str;
    }

    // 统计数据库中所有公交站点名，存入数组
    // 返回站点名
    public String[] getStation() {
        String station_name[] = null;
        int count = 0;
        // 建表时注意统一,一会看看重名的影响
        try {
            List<Site> list = siteService.getSiteList();
            station_name = new String[list.size()];
            for (Site item : list) {
                station_name[count] = item.getId()+"";//item.getName();
                count++;
            }
        } catch (Exception e) {
            System.out.println("执行时发生错误1!!!!");
        }
        return station_name;
    }
    // 统计数据库中所有公交路线，存入数组
    // 返回公交线路
    public String[] getBusline() {
        String busline[] = null;
        int count = 0;
        try {
            List<Route> list = routeService.getRouteList();
            busline = new String[list.size()];
            for (Route item : list) {
                busline[count] = item.getId()+"";//item.getName();
                count++;
            }
        } catch (Exception e) {
            System.out.println("执行时发生错误2！！！");
        }
        return busline;
    }
    // 统计数据库中每一线路经过的站点，存入数组
    // 需要参数line，区别每一路车
    // 返回站点名
    public String[] stationPerLine(String line) {
        String station_per_line[] = null;
        int count = 0;
        try {
            List<RouteSite> list = routeSiteService.getSitesByRouteList(Long.parseLong(line));
            station_per_line = new String[list.size()];
            for (RouteSite item : list) {
                station_per_line[count] = item.getSiteId()+"";//item.getSiteName();
                count++;
            }
        } catch (Exception e) {
            System.out.println("执行错误3！！！！");
        }
        return station_per_line;
    }
    // 统计经过某站点的所有公交车的组合
    // 需要参数station，表示经过的站点
    // 返回公交线路
    public String[] linePerStation(String station) {
        String line_per_station[] = null;
        int count = 0;
        try {
            List<RouteSite> list =  routeSiteService.getSitesByRouteList2(Long.parseLong(station));
            line_per_station = new String[list.size()];
            for (RouteSite item : list) {
                line_per_station[count] = item.getRouteId()+"";//item.getRouteName();
                count++;
            }
        } catch (Exception e) {
            System.out.println("执行错误4！！！");
        }
        return line_per_station;
    }


}
